using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using webapi.Domain.Repository;
using Webapi.Domain.Entity;

namespace webapi.Infrastructure.Filters
{
    public class ExceptionFilter : IAsyncExceptionFilter
    {
        private readonly IRepository<ExecetionLog> _ExecetionLog;
        public ExceptionFilter(IRepository<ExecetionLog> ExecetionLog)
        {
            _ExecetionLog = ExecetionLog;
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                string msg = context.Exception.Message;
                // context.Result =
                //     new ContentResult
                //     {
                //         // Content = string.Format("该错误位于{0},错误内容是:{1}", context.ActionDescriptor.ToString(), context.Exception.ToString()),
                //         // StatusCode = 200,
                //         // ContentType = "text/html;charset=utf-8"
                //         // _ExecetionLog.Add(new ExecetionLog{
                //         //     message = msg,
                //         //     execetion=context.Exception.ToString()
                //         // };
                //     };
                _ExecetionLog.Add(new ExecetionLog
                {
                    message = msg,
                    execetion = context.Exception.ToString()
                });
            }
            context.ExceptionHandled = true; //异常已处理了

            return Task.CompletedTask;
        }
    }
}